package com.test.qpbgboot.base.service.impl;

import com.cloopen.rest.sdk.CCPRestSmsSDK;
import com.test.qpbgboot.base.exception.ServiceException;
import com.test.qpbgboot.base.response.ResultStatus;
import com.test.qpbgboot.base.service.RedisService;
import com.test.qpbgboot.base.service.SMSService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class SMSServiceImpl implements SMSService {

    @Autowired
    private CCPRestSmsSDK smsSDK;
    @Autowired
    private RedisService redisService;

    @Override
    public void sendNewCaptcha(String phone) {
        log.debug("生成并发送验证码业务，参数:{}", phone);
        String phoneFrequency = "sms:" + phone + "frequency:";
        if (!redisService.checkValue(phoneFrequency, null)) {
            throw new ServiceException(ResultStatus.FREQUENT_OPERATIONS);
        }
        String phoneCaptcha = SMSService.getPhoneCaptchaRedisKey(phone);

        //设置短信模板ID
        String templateId = "1";
        //生成验证码
        String captcha = getCaptcha();
        //准备短信内容数据
        String[] dataList = {captcha,"10","1"};//dataList 数组中的元素顺序必须与模板中占位符的顺序一致
        //设置可选的扩展码
        String subAppend = "1234";  //可选 扩展码，四位数字 0~9999
        //获取第三方自定义消息id
        String reqId = getReqId();//可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        //调用SDK发送短信
        HashMap<String, Object> result = smsSDK.sendTemplateSMS(phone, templateId, dataList, subAppend, reqId);
        if ("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String, Object> data = (HashMap<String, Object>) result.get("data");
            for (String key : data.keySet()) {
                Object object = data.get(key);
                System.out.println(key + " = " + object);
            }
            //保存发送成功的短信记录

            redisService.setValue(phoneFrequency, "1", 1, TimeUnit.MINUTES);
            redisService.setValue(phoneCaptcha, captcha, 10, TimeUnit.MINUTES);
        }else {
            //异常返回输出错误码和错误信息
            throw new ServiceException(
                    Integer.valueOf((String) result.get("statusCode")),
                    (String) result.get("statusMsg"));
        }
    }

    private String getCaptcha() {
        String captcha = String.valueOf(System.currentTimeMillis());
        return captcha.substring(captcha.length() - 4);
    }

    private String getReqId() {
        return UUID.randomUUID().toString()
                .replace("-", "").substring(0, 32);
    }
}
